package com.example.mynote;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.drawerlayout.widget.DrawerLayout;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MainActivity extends BaseActivity implements AdapterView.OnItemClickListener,View.OnClickListener{
    private static final String TAG = "tag";

    private FloatingActionButton add_bnt;
    private Button delete_bnt,delete_all_bnt,delete_no_bnt,cancel_bnt;
    private LinearLayout bottom_nav;
    private NoteAdapter noteAdapter;
    private DrawerLayout drawerLayout;
    private Toolbar toolbar;
    private ListView listView;
    private TextView tv_sum;
    private LinearLayout setting_bnt,add_tag;


    // 列表数据
    private List<Note> noteList = new ArrayList<>();
    private List<Note> list_delete = new ArrayList<>();


    private boolean allCheckedFlag = false; // 全选按钮标志：用来更换图标

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        toolbar = findViewById(R.id.toolbar);
        drawerLayout = findViewById(R.id.drawer_layout);
        tv_sum = findViewById(R.id.tv_sum);
        bottom_nav = findViewById(R.id.bottom_nav);

        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) { // 分类功能及其他设置
            // 启动HomeAsUp按钮，默认是返回图标
            // actionBar.setDisplayHomeAsUpEnabled(true);
            // 设置案件图标
            // actionBar.setHomeAsUpIndicator(R.drawable.ic_baseline_dehaze_24);
        }
        // 设置导航的点击事件 也可以用onOptionsItemSelected方法
        // toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        //     @Override
        //     public void onClick(View v) {
        //         // 开启滑动菜单
        //         drawerLayout.openDrawer(GravityCompat.START);
        //     }
        // });
        // 创建数据库及表
        // LitePal.getDatabase();
        // 获取FloatingActionButton控件
        add_bnt = findViewById(R.id.fab);
        add_bnt.setOnClickListener(this);
        // 获取底部按钮
        delete_bnt = findViewById(R.id.delete_bnt);
        delete_all_bnt = findViewById(R.id.delete_all_bnt);
        cancel_bnt = findViewById(R.id.cancel_bnt);
        delete_no_bnt = findViewById(R.id.delete_no_bnt);
        //获取侧边菜单中的按钮
        setting_bnt = findViewById(R.id.setting_bnt);
        add_tag = findViewById(R.id.add_tag);
        // 按钮点击事件
        delete_bnt.setOnClickListener(this);
        delete_all_bnt.setOnClickListener(this);
        cancel_bnt.setOnClickListener(this);
        delete_no_bnt.setOnClickListener(this);
        setting_bnt.setOnClickListener(this);
        add_tag.setOnClickListener(this);

        // 初始化数据
        noteList = LitePal.findAll(Note.class);
        // 获取适配器
        noteAdapter = new NoteAdapter(MainActivity.this,R.layout.note_item,noteList);
        listView = (ListView) findViewById(R.id.list_view);
        listView.setAdapter(noteAdapter);
        listView.setOnItemClickListener(this);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // 设置菜单
        getMenuInflater().inflate(R.menu.main_menu,menu);
        // 获取菜单的搜索按钮
        MenuItem search_bnt = menu.findItem(R.id.menu_search);
        // 获取搜索视图
        SearchView search_view = (SearchView)search_bnt.getActionView();
        search_view.setQueryHint("搜索笔记");
        search_view.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                noteAdapter.getFilter().filter(newText);
                return false;
            }
        });

        return super.onCreateOptionsMenu(menu);
    }

    // EditActivity活动被销毁后，会回调这个函数
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 0: // 新建笔记
                if (resultCode == RESULT_OK) {
                    // 获取mode
                    int mode = data.getIntExtra("mode",0);
                    // 获取数据
                    String content = data.getStringExtra("content");
                    if (!content.trim().isEmpty()) {
                        // 获取当前时间
                        String time = data.getStringExtra("time");
                        // 创建笔记对象
                        Note note = new Note();
                        note.setContent(content);
                        Log.d(TAG, "添加新笔记");
                        note.setTime(time);
                        // 添加新笔记到litepal数据库
                        note.save();
                    }
                    // 刷新
                    refreshListView();
                }
                break;
            case 1: // 通过编辑界面来的
                if (resultCode == RESULT_OK) {
                    // 获取mode
                    int mode = data.getIntExtra("mode",0);
                    if(mode == 3) { // 修改笔记
                        Log.d(TAG, "修改了笔记");
                        // 获取数据
                        long id = data.getLongExtra("id", 0);
                        String content = data.getStringExtra("content");
                        String time =  data.getStringExtra("time");
                        String tag = data.getStringExtra("tag");
                        if (!content.trim().isEmpty()) {
                            Note note = new Note();
                            note.setId(id);
                            note.setContent(content);
                            note.setTime(time);
                            //直接根据id更新 或者用find和save方法组合更新也可以
                            note.update(note.getId());
                        } else {
                            // 内容为空，则自动删除这条笔记
                            LitePal.delete(Note.class,id);
                        }

                    }else if(mode == 2){ // 删除笔记
                        // 获取数据
                        long id = data.getLongExtra("id", 0);
                        LitePal.delete(Note.class,id);
                    }
                    // 刷新
                    refreshListView();
                    break;
                }
            default:
        }
    }

    public void refreshListView(){
        // 刷新ListView列表数据
        if(noteList.size() > 0) noteList.clear();
        noteList.addAll(LitePal.findAll(Note.class));
        noteAdapter.notifyDataSetChanged();
    }

    // ListView子项的点击事件
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if(!noteAdapter.isMultiSelect()){ // 不是批量删除
            Intent intent = new Intent(MainActivity.this, EditActivity.class);
            // Note note = noteList.get(position);
            Note note = noteAdapter.getItem(position);
            intent.putExtra("id",note.getId());
            intent.putExtra("content",note.getContent());
            intent.putExtra("time",note.getTime());
            intent.putExtra("mode",1); // 模式：点击编辑
            Log.d(TAG, "id=" + note.getId());
            startActivityForResult(intent,1);
            Log.d(TAG, "onItemClick: List View子项点击");
        }else {
            // 取得ViewHolder对象，这样就省去了通过层层的findViewById去实例化我们需要的cb实例的步骤
            NoteAdapter.ViewHolder holder = (NoteAdapter.ViewHolder) view.getTag();
            Note note = noteAdapter.getItem(position);
            /*
             * 如果CheckBox未选中，则点击后选中CheckBox，并将数据添加到list_delete中
             * 如果CheckBox选中，则点击后取消选中CheckBox，并将数据从list_delete中移除
             */
            if (holder.cb.isChecked()) {
                holder.cb.setChecked(false);
                HashMap<Integer, Boolean> isCheckedMap = noteAdapter.getIsCheckedMap();
                isCheckedMap.put(position, false);
                noteAdapter.setIsCheckedMap(isCheckedMap);
                list_delete.remove(note);
            } else {
                holder.cb.setChecked(true);
                HashMap<Integer, Boolean> isCheckedMap = noteAdapter.getIsCheckedMap();
                isCheckedMap.put(position, true);
                noteAdapter.setIsCheckedMap(isCheckedMap);
                list_delete.add(note);
            }
            // 如果手动全选,全选按钮样式需要变
            if(list_delete.size() == noteList.size()){
                // 控件显示与隐藏
                delete_all_bnt.setVisibility(View.VISIBLE);
                delete_no_bnt.setVisibility(View.GONE);
            }else {
                // 控件显示与隐藏
                delete_all_bnt.setVisibility(View.GONE);
                delete_no_bnt.setVisibility(View.VISIBLE);
            }
            tv_sum.setText("共选择了" + list_delete.size() + "条笔记");
        }
    }

    // 菜单点击事件
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                // drawerLayout.openDrawer(GravityCompat.START);
                break;
            case R.id.delete_checked:
                Log.d(TAG, "onOptionsItemSelected: 点击按钮");
                // 显示底部
                bottom_nav.setVisibility(View.VISIBLE);
                delete_all_bnt.setVisibility(View.GONE);
                delete_no_bnt.setVisibility(View.VISIBLE);
                tv_sum.setText("共选择了" + list_delete.size() + "条笔记");
                // 显示多选框
                noteAdapter.isMultiSelect(true);
                // 隐藏添加按钮
                add_bnt.setVisibility(View.INVISIBLE);
                // 刷新数据 noteAdapter.notifyDataSetChanged();
                refreshListView();

        }
        return true;
    }
    /*
    * 因为批量删除操作是只有 删除或者取消 按钮才会退出，
    * 所以在删除或者取消的点击事件里最后清空list_delete集合即可。
    * 或者每次批量删除操作之前清空集合。
    * */
    // 按钮点击事件
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.fab:{
                Intent intent = new Intent(MainActivity.this,EditActivity.class);
                startActivityForResult(intent,0);
            }
                break;
            case R.id.delete_bnt: {// 删除
                if(!list_delete.isEmpty()){
                    // 创建提示对话框
                    new AlertDialog.Builder(MainActivity.this)
                            .setMessage("确认要删除选中的笔记？")
                            .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    // 确认删除事件
                                    if(list_delete.size() == noteList.size()){
                                        //全部删除
                                        LitePal.deleteAll(Note.class);
                                    }else {
                                        // 根据id批量删除
                                        for(Note note:list_delete){
                                            Log.d(TAG, "onClick: " + note);
                                            LitePal.delete(Note.class,note.getId());
                                        }
                                    }
                                    // 清空集合
                                    list_delete.clear();
                                    // 设置多选框不显示
                                    noteAdapter.setMultiSelect(false);
                                    // 刷新
                                    refreshListView();
                                    // 底部隐藏
                                    bottom_nav.setVisibility(View.GONE);
                                    // 悬浮按钮显示
                                    add_bnt.setVisibility(View.VISIBLE);
                                    Toast.makeText(MainActivity.this,"删除成功！",Toast.LENGTH_SHORT).show();
                                }
                            })
                            .setNegativeButton(android.R.string.no,new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss(); //关闭对话框
                                }
                            }).create().show();
                }else {
                    Toast.makeText(MainActivity.this,"您还未选择任何笔记",Toast.LENGTH_SHORT).show();
                }
            }
                break;
            case R.id.cancel_bnt:{ // 取消
                noteAdapter.setMultiSelect(false); //退出选择模式
                // 刷新
                refreshListView();
                // 底部隐藏
                bottom_nav.setVisibility(View.GONE);
                // 悬浮按钮显示
                add_bnt.setVisibility(View.VISIBLE);
                // 清空
                list_delete.clear();
            }
            break;
            case R.id.delete_no_bnt:{ // 全部选中
                // 控件显示与隐藏
                delete_all_bnt.setVisibility(View.VISIBLE);
                delete_no_bnt.setVisibility(View.GONE);
                // 需要清空剩余数据
                list_delete.clear();
                // 将list数据全部加入删除集合中
                for(Note note:noteList){
                    list_delete.add(note);
                }
                tv_sum.setText("共选择了" + list_delete.size() + "条笔记");
                // 将适配器中的所有数据变为选中状态
                noteAdapter.isCheckedALL(true);
                // 刷新适配器
                noteAdapter.notifyDataSetChanged();
            }
            break;
            case R.id.delete_all_bnt:{ // 全部不选中
                list_delete.clear();
                Log.d(TAG, "onClick: " + noteList.size());
                // 控件显示与隐藏
                delete_all_bnt.setVisibility(View.GONE);
                delete_no_bnt.setVisibility(View.VISIBLE);
                // 清除数据
                list_delete.clear();
                tv_sum.setText("共选择了" + list_delete.size() + "条笔记");
                // 取消选中
                noteAdapter.isCheckedALL(false);
                // 刷新适配器
                noteAdapter.notifyDataSetChanged();
            }
            break;
            case R.id.add_tag:
                final EditText et = new EditText(this);
                new AlertDialog.Builder(MainActivity.this)
                        .setMessage("输入新的标签名")
                        .setView(et)
                        .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                 Toast.makeText(MainActivity.this, et.getText().toString(), Toast.LENGTH_SHORT).show();
                                 // 更新数据库中的数据，更新适配器数据...
                            }
                        }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).create().show();

                break;
            // 未开发：设置
            case R.id.setting_bnt:
                Log.d(TAG, "onClick: 111");
                // 跳转页面
                Intent intent = new Intent(MainActivity.this,SettingActivity.class);
                startActivity(intent);
                break;
            default:
        }

    }
}